package club.cearnach.api.service.impl;

import club.cearnach.api.dao.IDirectorDao;
import club.cearnach.entity.Director;
import club.cearnach.entity.Person;
import club.cearnach.api.service.IDirectorService;
import club.cearnach.api.service.IPersonService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Optional;

/**
 * @author 阮胜
 * @date 2018/5/12 17:03
 */
@Service
public class DirectorServiceImpl implements IDirectorService {
    private final IDirectorDao directorDao;
    private final IPersonService personService;

    public DirectorServiceImpl(IDirectorDao directorDao, IPersonService personService) {
        this.directorDao = directorDao;
        this.personService = personService;
    }

    @Override
    public Director save(Director director) {
        linkPerson(director);
        return directorDao.save(director);
    }

    @Override
    public Director saveAndFlush(Director director) {
        linkPerson(director);
        return directorDao.saveAndFlush(director);
    }

    /**
     * 与person建立联系
     *
     * @param director
     */
    private void linkPerson(Director director) {
        Optional<Director> ac = directorDao.findByName(director.getName());
        ac.ifPresent(actor1 -> BeanUtils.copyProperties(actor1, director));
        Person person = personService.findByNameOne(director.getName());
        director.setPerson(person);
    }

    @Override
    public Optional<Director> findByName(String name) {
        return directorDao.findByName(name);
    }

    @Override
    public HashSet<Director> saveMany(String directors) {
        HashSet<Director> directorSet = new HashSet<>();
        if (!StringUtils.isEmpty(directors)) {
            String[] directorArr = directors.split("/");
            for (String director : directorArr) {
                Director ac = saveAndFlush(new Director(director));
                directorSet.add(ac);
            }
        }
        return directorSet;
    }

    @Override
    public Optional<Director> findByPersonId(Integer id) {
        return directorDao.findByPersonId(id);
    }

    @Override
    public void delete(Integer id) {
        directorDao.deleteById(id);
    }
}
